package com.zhang.shopcar.utils;

import java.io.IOException;
import java.nio.charset.Charset;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

/**
 * Created by turbo on 2016/12/20.
 * 自定义判断Token是否过期拦截器
 */

public class MyInterceptor implements Interceptor {
    private static final Charset UTF8 = Charset.forName("UTF-8");
    private String mErrodCode;
    private String mAcctionToken;

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);
        // LogUtil.print("response.code=" + response.code());


        // Log.i("body---------->", basicBean.getErrorCode().toString());

        // Log.i("body---------->",  bodyString+"");


        /***************************************/
        ResponseBody responseBody = response.body();
        BufferedSource source = responseBody.source();
        try {
            source.request(Long.MAX_VALUE); // Buffer the entire body.
            Buffer buffer = source.buffer();
            Charset charset = UTF8;
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }
            String bodyString = buffer.clone().readString(charset);
          /*  if (bodyString.contains("用户token超时")) {
                Gson gson = new Gson();
                BasicBean basicBean = gson.fromJson(bodyString, BasicBean.class);
                mErrodCode = basicBean.getErrorCode();
                if (mErrodCode.equals("-102")) {

                    String refreshToken1 = UIUtils.mSp.getString(Constants.REFRESHTOKEN1, "");
                    Map<String, String> refreshMap = new HashMap<>();


                    refreshMap.put("refreshToken1", UIUtils.jiami(refreshToken1));
                    refreshMap.put("appPubKey", Constants.ANDROID_PUBLIC_KEY);
//获取实例
                    Retrofit retrofit = new Retrofit.Builder()
                            //设置OKHttpClient,如果不设置会提供一个默认的
                            .client(new OkHttpClient())
                            //设置baseUrl
                            .baseUrl(Constants.BASEURL)
                            //添加Gson转换器
                            .addConverterFactory(GsonConverterFactory.create())
                            .build();

                    RefereshService service = retrofit.create(RefereshService.class);

                    Call<BasicBean> call = service.loadRepo(refreshMap);

                    retrofit2.Response<BasicBean> repos = call.execute();
                    BasicBean tokenBean = repos.body();
                    mAcctionToken = UIUtils.jiemi(tokenBean.getData().getAcctionToken1());
                    UIUtils.mSp.putString(Constants.ACCESSTOKEN1, mAcctionToken);


                    //使用新的Token，创建新的请求
                    Request newRequest = chain.request().newBuilder().header("accessToken1", UIUtils.jiami(mAcctionToken)).build();
                    //重新请求
                    response.body().close();
                    return chain.proceed(newRequest);


                }
            }*/


        } catch (IOException e) {
            e.printStackTrace();
        }

        return response;
    }

    /**
     * 根据Response，判断Token是否失效
     *
     * @param response
     * @return
     */
    private boolean isTokenExpired(Response response) {


        return false;
    }


       /* String refreshToken1 = UIUtils.mSp.getString(Constants.REFRESHTOKEN1, "");

        Map<String, String> refreshMap = new HashMap<>();


        refreshMap.put("refreshToken1", UIUtils.jiami(refreshToken1));
        ComicServer.refreshToken(refreshMap, new RxSubscribe<TokenBean>(UIUtils.getContext()) {


            @Override
            protected void _onNext(TokenBean tokenBean) {
              *//*  String errorCode = tokenBean.getErrorCode();
                if (errorCode.equals("0")) {
                    TokenBean.DataBean dataBean = tokenBean.getData();
                    UIUtils.mSp.putString(Constants.ACCESSTOKEN1, dataBean.getAcctionToken1());
                }*//*
            }

            @Override
            protected void _onError(String message) {

            }
        });
        return null;*/


}